package com.example.searchjavaapi.api;

import com.example.searchjavaapi.searcher.Result;

import com.example.searchjavaapi.searcher.Searcher;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/search")
public class Search {

    @Autowired
    private Searcher searcher;
    private Gson gson = new GsonBuilder().create();

    public Search() throws IOException {

    }


    @RequestMapping("search1")
    public void search(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        resp.setContentType("application/json;charset=utf-8");
        String query = req.getParameter("query");
        if (query==null||query.equals("")){
            resp.setStatus(404);
            resp.getWriter().write("query参数非法");
            return;
        }
        List<Result> results = searcher.search(query);
        String respString = gson.toJson(results);
        resp.getWriter().write(respString);

    }




}
